package com.controller.sys;

import com.alibaba.fastjson.JSON;
import com.common.DateUtils;
import com.common.DesUtils;
import com.common.StringUtils;
import com.common.db.RedisUtils;
import com.common.easyui.EasyuiUtils;
import com.common.easyui.JsonTreeData;
import com.common.http.HttpResult;
import com.common.model.ActionEnum;
import com.common.model.Global;
import com.common.model.UserTypeEnum;
import com.common.spring.SpringMvcUtils;
import com.dao.sys.LogDao;
import com.dao.sys.SysManageMapper;
import com.dao.sys.SysUserMapper;
import com.dao.task.TaskMapper;
import com.model.supply.SupplyUserModel;
import com.model.sys.LogModel;
import com.model.sys.LoginModel;
import com.model.sys.SysUser;
import com.service.sys.WXService;

import freemarker.ext.beans.HashAdapter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(value = "/api")
public class LoginController {
	static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysManageMapper sysManageMapper;
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	LogDao logDao;
	@Autowired
	WXService wxService;

	@RequestMapping(value = "/loginMobile", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult loginMobile(HttpServletRequest request, @RequestParam String hi) {
		if (!StringUtils.isNotNull(hi)) {
			return HttpResult.error("用户HI账号不存在！");
		}
		String loginnameString = hi;
		// 通过hi获取用户信息
//			loginnameString = "chenjun";
		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("casid", loginnameString);
		SysUser sysUser = sysUserMapper.selectByCasName(hashMap);
		if (sysUser == null) {
			return HttpResult.error("用户名密码错误！");
		} else {
			HttpResult httpResult = new HttpResult();
			LoginModel loginModel = new LoginModel();
			sysUser.setPwd("");
			loginModel.setSysUser(sysUser);
			loginModel.setUserTypeString(UserTypeEnum.XYUser.getValue());
			String tokenString = sysUser.getUserid() + "," + System.currentTimeMillis() + ","
					+ UserTypeEnum.XYUser.getValue();
			try {
				loginModel.setTokenString(DesUtils.encrypt(tokenString, DesUtils.getKey()));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error(e.getMessage());
				e.printStackTrace();
			}
			httpResult.setData(loginModel);
			request.getSession().setAttribute("userType", UserTypeEnum.XYUser.getValue());
			request.getSession().setAttribute("sysUser", sysUser);
			redisUtils.set(Global.REDIS_USER_PREFIX + UserTypeEnum.XYUser.getValue() + "-" + sysUser.getUserid(),
					sysUser, Global.PC_BACKGROUND_TOKEN_EXPIRE);
			LogModel logModel = new LogModel();
			logModel.setLogId(UUID.randomUUID().toString());
			logModel.setLogContent("登录");
			logModel.setLogAction(ActionEnum.login.getName());
			logDao.insert(logModel);
			return httpResult;
		}
	}

	@RequestMapping(value = "/sys/loginin", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult sysloginin(HttpServletRequest request, @RequestParam String loginName, @RequestParam String pwd) {
		try {
			SysUser sysUser = sysUserMapper.selectByNamePwd(loginName, DesUtils.encrypt(pwd));
			if (sysUser == null) {
				return HttpResult.error("用户名密码错误！");
			} else {
				HttpResult httpResult = new HttpResult();
				LoginModel loginModel = new LoginModel();
				sysUser.setPwd("");
				loginModel.setSysUser(sysUser);
				loginModel.setUserTypeString(UserTypeEnum.XYUser.getValue());
				String tokenString = sysUser.getUserid() + "," + System.currentTimeMillis() + ","
						+ UserTypeEnum.XYUser.getValue();
				loginModel.setTokenString(DesUtils.encrypt(tokenString, DesUtils.getKey()));
				List<HashMap<String, Object>> permiHashMaps = sysManageMapper
						.selectUrlAndPermissionMap(sysUser.getUserid());
				loginModel.setBtnPermission(permiHashMaps);
				httpResult.setData(loginModel);
				request.getSession().setAttribute("userType", UserTypeEnum.XYUser.getValue());
				request.getSession().setAttribute("sysUser", sysUser);
				redisUtils.set(Global.REDIS_USER_PREFIX + UserTypeEnum.XYUser.getValue() + "-" + sysUser.getUserid(),
						sysUser, Global.PC_BACKGROUND_TOKEN_EXPIRE);
				LogModel logModel = new LogModel();
				logModel.setLogId(UUID.randomUUID().toString());
				logModel.setLogContent("登录");
				logModel.setLogAction(ActionEnum.login.getName());
				logDao.insert(logModel);
				return httpResult;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("errorMessage:{}", e.getMessage());
			return HttpResult.error(e.getMessage());
		}
	}

	@RequestMapping(value = "/sys/selectUsers", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String selectUsers(HttpServletRequest request) {
		try {
			HashMap<String, Object> hashtable = new HashMap<>();
			String queryName = request.getParameter("queryName");
			if (queryName != null && !queryName.equals("")) {
				hashtable.put("queryName", queryName);
			}
			List<HashMap<String, Object>> list = sysManageMapper.selectUsers(hashtable);
			String jsonString = JSON.toJSONString(list);
//			jsonString = EasyuiUtils.getDatagridPageJson(jsonString, taskMapper.selectCount(hashtable));
			logger.info("selectUsers:{}", jsonString);
			return jsonString;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("selectUsers:{}", e.getMessage());
			return e.getMessage();
		}
	}

	@RequestMapping(value = "/sys/selectModuleMap", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String selectModuleMap(HttpServletRequest request) {
		try {
			SysUser sysUser = (SysUser) request.getSession().getAttribute("sysUser");
			String userid = sysUser.getUserid();
			logger.debug("userid:{}", userid);
			List<HashMap<String, Object>> list = sysManageMapper.selectModuleMap(userid);
			List<JsonTreeData> treeDataList = new ArrayList<JsonTreeData>();
			for (Map<String, Object> map : list) {
				JsonTreeData treeData = new JsonTreeData();
				treeData.setId(map.get("MODULEID".toLowerCase()).toString());
				treeData.setPid(map.get("PARENTMODULEID".toLowerCase()).toString());
				treeData.setText(map.get("MODULENAME".toLowerCase()).toString());
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("url", map.get("MODULEURL".toLowerCase()).toString());
				treeData.setAttributes(attributes);
				treeDataList.add(treeData);

			}
			List<JsonTreeData> newTreeDataList = EasyuiUtils.getTreeJson(treeDataList, "0", "");

			// JSONArray jsonarray = JSONArray.fromObject(newTreeDataList);
			String slist = JSON.toJSONString(newTreeDataList);
			// System.out.println(slist);
			logger.info("treelist测试:{}", list);
			// request.setAttribute("addLists", list);
			return slist;
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("errorMessage", "" + e.getMessage());
			logger.error("errorMessage:{}", e.getMessage());
			return "test/test";
		}
	}

	@RequestMapping(value = "/sys/logoff", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult logoff() {
		SysUser sysUser = SpringMvcUtils.getSysUser();
		redisUtils.del(Global.REDIS_USER_PREFIX + UserTypeEnum.XYUser.getValue() + "-" + sysUser.getUserid());
		HttpServletRequest httpServletRequest = SpringMvcUtils.getHttpServletRequest();
		httpServletRequest.getSession().invalidate();
		return HttpResult.ok();
	}
}
